var _historyTpl   = '';
var _popupContent = '';
var _memberCode   = '';
var _couponsList  = [];
var _priceRate    = 1;

function selectedRows () {
    var ids  = new Array();
    var rows = Ext.select('tr.trSelected', false, 'stokistlist').elements;
    Ext.each(rows, function(r){
        ids.push(Ext.fly(r).down('td div').dom.innerHTML);
    });

    if (ids.length == 0) {
        return 0;
    } else if (ids.length == 1) {
        return ids[0];
    }

    return ids;
} // selectedRows

function populate (data) {
    Ext.each(data, function(d){
        var f = Ext.get(d.f);

        if (f) {
            if (f.dom.type == 'text' || f.dom.type == 'textarea' || f.dom.type == 'hidden') {
                f.dom.value = d.v;
            } else if (f.dom.type == 'select-one') {
                var i = 0;
                Ext.each(f.dom.options, function(o){
                    if (o.value == d.v) {
                        f.dom.options.selectedIndex = i;
                    }
                    i++;
                });
            }
        }
    });
} // populate

function addnew () {
    openPopup('stockist-wrap', 'Add New Stockist');
} // addnew

function editRecord (id) {
    var mesg = Ext.get('popup-message');

    if (!id) {
        message('Record Id not found.');
        return;
    }

    openPopup('stockist-wrap', 'Edit Product Info');

    transId = Ext.Ajax.request({
        url: _webroot+'/admin/stockists/get/'+id,
        method: 'GET',
        success: function(response, opts) {
            var obj = Ext.decode(response.responseText);

            if (obj.status == 1) {
                populate(obj.data);
            } else if (obj.mesg) {
                mesg.update(obj.mesg);
                mesg.addClass('error').highlight();
            }
        },
        failure: function(response, opts) {
            message('server-side failure with status code '+response.status);
        },
        callback: function() {
            Ext.fly('popup-progress').ghost('b', { useDisplay:true });
            Ext.each(Ext.query('input[type=submit],input[type=button]', 'form-stockist'), function(e){ e.disabled = false; });
        }
    });

    if (Ext.Ajax.isLoading(transId)) {
        Ext.each(Ext.query('input[type=submit],input[type=button]', 'form-stockist'), function(e){ e.disabled = true; });
        Ext.fly('popup-progress').update('Loading..');
        Ext.fly('popup-progress').fadeIn();
    }
} // editRecord

function updateRecord (act) {
    var ids = selectedRows();
    var act = act.toLowerCase();

    if (!ids) {
        message('Please select the row that want to '+act+'.');
        return;
    }
    if (Ext.isArray(ids)) {
        var id = ids.join(',');
    } else {
        var id = ids;
    }

    var mesg = Ext.isArray(ids) ? 'these '+ids.length+' selected records' : 'this selected record';
    if (!confirm('Are you sure you want to '+act+' '+mesg+'?')) {
        return;
    }

    transId = Ext.Ajax.request({
        url: _webroot+'/admin/products/update_status/',
        method: 'POST',
        params: 'id='+id+'&task='+act,
        success: function(response, opts) {
            var obj = Ext.decode(response.responseText);

            if (obj.status == 1) {
                reload_grid();
            } else if (obj.error) {
                message(obj.error);
            }
        },
        failure: function(response, opts) {
            message('server-side failure with status code '+response.status);
        },
        callback: function() {

        }
    });
} // updateRecord

function openPopup (el, title) {
    clearPopup();

    _popupContent = el;

    Ext.fly('popup-title').update(title);
    Ext.fly(el).show();
    Ext.get('popup').setStyle({
        top: '128px',
        left: '380px'
    }).syncFx().slideIn().fadeIn({ duration:0.8});
} // openPopup

function closePopup () {
    Ext.fly('popup').ghost('b', {
        useDisplay: true,
        callback: clearPopup
    });
    Ext.select('tr.trSelected', false, 'stokistlist').removeClass('trSelected');
} // closePopup

function clearPopup () {
    Ext.select('div.popup_content{display!=none}', false, 'popup_content').setStyle({ display:'none' });
    Ext.fly('popup-message').setStyle({ display:'none' });
    clearForm();
} // clearPopup

function clearForm () {
    Ext.each(Ext.query('select option:first-child', 'form-pos'), function(e){ e.selected = true; });
    Ext.each(Ext.query('input.input, input[type=hidden], textarea.input', 'form-pos'), function(e){ e.value = ''; });
    Ext.each(Ext.query('input.date', 'form-pos'), function(e){ e.value = 'select..'; });
    Ext.each(Ext.query('input.qty', 'form-pos'), function(e){ e.value  = ''; });
} // clearForm

function getCoupons () {
    var member_code = Ext.fly('member-code').getValue();
    var message     = Ext.get('message');

    message.hide();

    if (!member_code) {
        message.update('User Id required');
        message.addClass('error').highlight();
        Ext.fly('member-code').focus();
        return false;
    }

    Ext.select('div.coupon', false, 'coupon-body').update('&nbsp;');

    transId = Ext.Ajax.request({
        url: _webroot+'/admin/coupon_histories/search/'+member_code,
        method: 'GET',
        success: function(response, opts) {
            var obj = Ext.decode(response.responseText);

            if (obj.status == 1) {
                _couponsList = obj.list;
                var options;

                if (_couponsList.length > 0) {
                    Ext.each(_couponsList, function(d){
                        options += '<option value="'+d.id+'">'+d.code+'</option>'
                    });
                    Ext.fly('coupon-list').update('<select id="coupon_id" name="coupon_id" class="select" onchange="pickCoupon()"><option value="">select..</option>'+options+'</select>');
                } else {
                    Ext.fly('coupon-list').update('');
                }
            } else if (obj.mesg) {
                mesg.update(obj.mesg);
                message.addClass('error').highlight();
            }
        },
        failure: function(response, opts) {
            message('server-side failure with status code '+response.status);
        },
        callback: function() {
            Ext.fly('check-coupon').dom.value    = 'Check';
            Ext.fly('check-coupon').dom.disabled = false;
        }
    });

    if (Ext.Ajax.isLoading(transId)) {
        Ext.fly('check-coupon').dom.value    = 'checking..';
        Ext.fly('check-coupon').dom.disabled = true;
    }
} // getCoupons

function pickCoupon () {
    var id = Ext.fly('coupon_id').getValue();

    if (!id) {
        clearCoupon(0);
        return;
    }

    Ext.each(_couponsList, function(d){
        if (id == d.id) {
            Ext.fly('coupon-total').highlight().update(d.total);
            Ext.fly('coupon-balance').highlight().update(d.balance);
            Ext.fly('coupon-created').highlight().update(d.created);
            Ext.fly('coupon-lastUse').highlight().update(d.lastUse);
            Ext.fly('coupon-action').show();
            Ext.fly('useCoupon').dom.checked = false;
            toggleCoupon();

            if (d.total == d.balance) {
                Ext.fly('buy-coupon').highlight();
                Ext.fly('use-coupon').setStyle({ display:'none' });
            } else {
                Ext.fly('buy-coupon').setStyle({ display:'none' });
                Ext.fly('use-coupon').highlight();
            }
        }
    });
} // pickCoupon

function checkRanking () {
    if (Ext.fly('ac_results') != null && Ext.fly('ac_results').isVisible()) {
        return;
    }

    var member_code = Ext.fly('member-code').getValue();
    var message     = Ext.get('message');

    message.hide();

    if (!member_code || _memberCode == member_code) {
//console.log('no code or same code = '+member_code);
        return false;
    } else if (_memberCode != member_code) {
//console.log('changed');
        _memberCode = member_code;
    }

    Ext.select('div.coupon', false, 'coupon-body').update('&nbsp;');

    transId = Ext.Ajax.request({
        url: _webroot+'/admin/members/check_ranking/'+member_code,
        method: 'GET',
        success: function(response, opts) {
            var obj = Ext.decode(response.responseText);

            if (obj.status == true) {
                _priceRate = obj.priceRate;
                sumTotal();
            } else if (obj.mesg) {
                mesg.update(obj.mesg);
                message.addClass('error').highlight();
            }
        },
        failure: function(response, opts) {
            message('server-side failure with status code '+response.status);
        },
        callback: function() {

        }
    });

    if (Ext.Ajax.isLoading(transId)) {

    }
} // checkRanking

function clearCoupon (all) {
    if (all) {
        Ext.fly('coupon-list').update('');
    }
    Ext.fly('coupon-total').update('&nbsp;');
    Ext.fly('coupon-balance').update('&nbsp;');
    Ext.fly('coupon-created').update('&nbsp;');
    Ext.fly('coupon-lastUse').update('&nbsp;');
    Ext.fly('coupon-action').setStyle({ display:'none' });
    Ext.fly('coupon-action').up('td').setStyle({ background:'none' });
    Ext.fly('coupon-tbl').setStyle({ display:'none' });
    Ext.fly('useCoupon').dom.checked = false;
    sumTotal();
} // clearCoupon

function toggleCoupon () {
    sumTotal();

    if (Ext.fly('useCoupon').dom.checked) {
        Ext.fly('coupon-action').up('td').setStyle({ background:'#DDFFDD' });
        Ext.select('span.fLeft', false, 'coupon-action').addClass('green');
        Ext.fly('coupon-tbl').stopFx().fadeIn();
        Ext.fly('total-bv').update(0);
    } else {
        Ext.fly('coupon-action').up('td').setStyle({ background:'none' });
        Ext.select('span.fLeft', false, 'coupon-action').removeClass('green');
        Ext.fly('coupon-tbl').fadeOut({ useDisplay:true });
    }
} // toggleCoupon

function init_ac () {
    $("#member-code").autocomplete(_webroot+'/admin/members/search/', {
        minChars: 1,
        max: 12,
        autoFill: false,
        mustMatch: true,
        matchContains: false,
        width: 260,
        scrollHeight: 260,
        formatItem: function(row) {
            return row[1]+' ('+row[2]+') '+row[3];
        },
        formatResult: function(row) {
            clearCoupon(1);

            if (typeof(row[1]) == 'undefined') {
                return;
            }

            return row[1].replace(/(<.+?>)/gi, '');
        }
    });
} // init_ac

function init_calendar () {
    var date1 = Calendar.setup({
        inputField: 'date',
        trigger: 'show-date',
        dateFormat: '%Y/%m/%d', align: 'Br', showTime: false, minuteStep: 1,
        onSelect: function(date1) {
            var date = date1.selection.print('%a, %e %B %Y');
            if (date.length > 0) {
                Ext.fly('show-date').dom.value = date.join('');
            }
            date1.hide();
        }
    });

    $("#time").clockpick({
        starthour: 0,
        endhour: 23,
        minutedivisions: 12,
        event: 'focus',
        layout: 'horizontal'
    });
} // init_calendar

function save () {
    var proceed = true;
    var transId = '';
    var focuson = '';
    var message = Ext.get('message');

    message.setStyle({ display:'none' });
    Ext.select('.invalid', false, 'form-pos').removeClass('invalid');
    Ext.select('div.invalidField', false, 'form-pos').remove();
    Ext.select('td.invalidText', false, 'form-pos').removeClass('invalidText');
    Ext.each(Ext.select('.req', false, 'form-pos').elements, function(e){
        var el = Ext.get(e);

        if (!el.getValue() || el.getValue() == 'select..') {
            proceed = false;
            el.addClass('invalid');
            el.up('td').prev('td').addClass('invalidText');
            if (!focuson) {
                focuson = e.id;
                el.focus();
                el.fadeIn({
                    duration: 2.0
                });
            }
        }
    });

    if (!proceed) {
        return false;
    }

    transId = Ext.Ajax.request({
        form: 'form-pos',
        success: function(response, opts) {
            var obj = Ext.decode(response.responseText);
            if (obj.status == false) {
                if (obj.mesg) {
                    message.update(obj.mesg);
                    message.addClass('error').highlight();
                }
                if (Ext.isArray(obj.error)) {
                    Ext.each(obj.error, function(e) {
                        var el  = Ext.get(e.id);
                        var err = '<div class="invalidField" style="display:none;">'+e.code+'</div>';
                        el.addClass('invalid');
                        el.up('td').prev('td').addClass('invalidText');
                        el.insertHtml('afterEnd', err);
                        el.next('div.invalidField').slideIn('t', {
                            duration:.4
                        });
                        if (!focuson) {
                            focuson = e.id;
                            el.focus();
                            el.fadeIn({
                                duration: 2.0
                            });
                        }
                    });
                }
            } else {
                if (obj.mesg) {
                    message.update(obj.mesg);
                    message.removeClass('error').addClass('success').highlight();
                    message.pause(8).fadeOut({ useDisplay:true });
                }
                clearCoupon(1);
                clearForm();
            }
        },
        failure: function(response, opts) {
            console.log('server-side failure with status code '+response.status);
        },
        callback: function() {
            Ext.fly('progress').ghost('b', { useDisplay:true });
            Ext.each(Ext.query('input[type=submit],input[type=button]', 'form-pos'), function(e){ e.disabled = false; });
        }
    });

    if (Ext.Ajax.isLoading(transId)) {
        Ext.each(Ext.query('input[type=submit],input[type=button]', 'form-pos'), function(e){ e.disabled = true; });
        Ext.fly('progress').update('Saving..');
        Ext.fly('progress').fadeIn();
    }

    return false;
} // save

function number_format (number, decimals, dec_point, thousands_sep) {
    var n = number, prec = decimals;
    var toFixedFix = function (n,prec) {
        var k = Math.pow(10,prec);
        return (Math.round(n*k)/k).toString();
    };

    n = !isFinite(+n) ? 0 : +n;
    prec = !isFinite(+prec) ? 0 : Math.abs(prec);
    var sep = (typeof thousands_sep === 'undefined') ? ',' : thousands_sep;
    var dec = (typeof dec_point === 'undefined') ? '.' : dec_point;

    var s = (prec > 0) ? toFixedFix(n, prec) : toFixedFix(Math.round(n), prec); //fix for IE parseFloat(0.55).toFixed(0) = 0;

    var abs = toFixedFix(Math.abs(n), prec);
    var _, i;

    if (abs >= 1000) {
        _ = abs.split(/\D/);
        i = _[0].length % 3 || 3;

        _[0] = s.slice(0,i + (n < 0)) +
              _[0].slice(i).replace(/(\d{3})/g, sep+'$1');
        s = _.join(dec);
    } else {
        s = s.replace('.', dec);
    }
    if (s.indexOf(dec) === -1 && prec > 1) {
        s += dec+new Array(prec).join(0)+'0';
    }
    return s;
} // number_format

function sumTotal () {
            var totalBv     = 0;
            var totalPrice  = 0;
            var totalPrice2 = 0;
            var totalQty    = 0;

            Ext.each(Ext.query('input.qty', 'product-list'), function(q){
                var qty = parseInt(q.value);
                if (qty > 0) {
                    var id = q.id;
                    var bv = parseInt(Ext.fly('bv'+id).dom.innerHTML);
                    var p1 = parseFloat(Ext.fly('p1'+id).dom.innerHTML);
                    var p2 = parseFloat(Ext.fly('p2'+id).dom.innerHTML);
                    p1 = (p1 > 0) ? p1 : 0;
                    p2 = (p2 > 0) ? p2 : 0;

                    totalBv     += bv * qty;
                    totalPrice  += p1 * qty;
                    totalPrice2 += p2 * qty;
                    totalQty    += qty;
                }
            });

            if (Ext.fly('useCoupon').dom.checked) { // use coupon
                var id = Ext.fly('coupon_id').getValue();

                Ext.fly('sales-bv').update(0);
                Ext.fly('total-bv').update(0); // purchase with coupon got no BV
                Ext.each(_couponsList, function(d){
                    if (id == d.id) {
                        var newBalance = parseFloat(d.balance) - totalPrice2;
                        Ext.fly('deduct-coupon').update(d.balance);

                        if (newBalance > 0) { // enough for deduct sales total
                            if (d.total == d.balance) { // new purchase coupon
                                Ext.fly('sub-total').update('100.00');
                            } else { // use existing bought coupon
                                Ext.fly('sub-total').update('0.00');
                            }

                            Ext.fly('new-coupon-balance').update(number_format(newBalance, 2));
                        } else { // coupon value not enough
                            if (d.total == d.balance) {
                                var subtotal = Math.abs(newBalance) + 100;
                            } else {
                                var subtotal = Math.abs(newBalance);
                            }

                            Ext.fly('new-coupon-balance').update('0.00');
                            Ext.fly('sub-total').update(number_format(subtotal * _priceRate, 2));
                        }
                    }
                });
            } else {
                Ext.fly('sales-bv').update(totalBv);
                Ext.fly('total-bv').update(totalBv);
                Ext.fly('sub-total').update(number_format(totalPrice * _priceRate, 2));
            }

            Ext.fly('total-price').update(number_format(totalPrice,2));
            Ext.fly('total-member-price').update(number_format(totalPrice2,2));
            Ext.fly('sub-total2').update('-'+number_format(totalPrice * _priceRate, 2));
            Ext.fly('total-qty').update(totalQty);
} // sumTotal

function message (msg, focus) {
    alert(msg);

    if (typeof focus != 'undefined') {
        Ext.fly(focus).focus();
    }
} // message

function init (){
    init_ac();
    init_calendar();
                  // bc tb <-  ->  del  0  1  2  3  4  5  6  7  8  9   0  1  2  3   4   5   6   7   8   9
    var validCode = [8, 9, 37, 39, 46, 48,49,50,51,52,53,54,55,56,57, 96,97,98,99,100,101,102,103,104,105];
    Ext.select('input.qty', false, 'product-list').on('keydown', function(e, t){
        if (validCode.indexOf(e.keyCode) == -1) {
            e.stopEvent();
        }
    });
    Ext.select('input.qty', false, 'product-list').on('keyup', function(e, t){
        if (validCode.indexOf(e.keyCode) != -1) {
            sumTotal();
        }
    });
    Ext.fly('member-code').on('blur', function(e, t){
        setTimeout(checkRanking, 2000);
    });
}// init